const audioCtx = wx.createInnerAudioContext()
Page({
  data: {
    islove: false, //是否添加到喜欢
    isplay: false, // 是否播放
    musicPercent: 0, // 进度条百分比
    duration: 0, // 歌曲总时长
    currentTime: 0, // 当前播放时间
  },
  // 监听页面加载
  onLoad() {
    // 加载资源
    audioCtx.src = "/audio/journey.mp3"
  },
  onList: function () {
    wx.navigateTo({
      url: '/pages/publicmusic/publicmusic',
    })
  },
  // 改变是否喜欢
  onlove: function () {
    this.setData({
      islove: !this.data.islove
    })
  },
  // 播放
  onplay: function () {
    this.setData({
      isplay: true
    })
      // 播放
      audioCtx.play();
      console.log("音乐播放开始");
      // 监听音乐进度条变化
      audioCtx.onTimeUpdate(() => {
      this.updateProgress()
    })
    // 监听播放结束事件
      audioCtx.onEnded(() => {
        this.setData({
          musicPercent: 0,
          duration: 0,
          currentTime: 0
        })
      })
  },
  // 暂停
  onpause() {
    audioCtx.pause()
    this.setData({
      isplay: false,
    })
  },
  // 更新进度条
  updateProgress: function () {
    const currentTime = audioCtx.currentTime
    const duration = audioCtx.duration 
    this.setData({ 
      musicPercent: currentTime/duration*100, //进度条百分比
      currentTime: this.formdate(Math.ceil(currentTime)), // 当前时间
      duration: this.formdate(Math.ceil(duration)) //歌曲总时长
    })
  },
  // 播放时间格式化
  formdate: function (seconds) {
    const minute = Math.floor(seconds/60)
    const second = seconds%60
    if(minute < 10 && second < 10) {
      return `0${minute}:0${second}`
    }else if(minute < 10 && second >= 10) {
      return `0${minute}:${second}`
    }else if (minute >= 10 && second < 10){
      return `${minute}:0${second}`
    }else {
      return `${minute}:${second}`
    }
  },
  onList() {
    wx.navigateTo({
      url: '/pages/publicmusic/publicmusic',
    })
  },
  goToShowLrc() {
    wx.navigateTo({
      url: '/pages/showLrc/showLrc',
    })
  }
})